/**
 * 
 */
package com.syncshot.androidapp.util;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

import android.content.Context;
import android.util.Log;

/**
 * @author Stan
 * 
 */
public class Parser {
    /** Used locally to tag Logs */
    private static final String    TAG       = "Parser";

    private static ObjectMapper mObjectMapper;

    // ///////////////////

    private static volatile Parser mInstance = null;

    private Parser() {
        if (mObjectMapper == null) {
            mObjectMapper = new ObjectMapper();
            mObjectMapper.configure(SerializationConfig.Feature.AUTO_DETECT_GETTERS, false);
            mObjectMapper.configure(SerializationConfig.Feature.AUTO_DETECT_FIELDS, false);
            mObjectMapper.configure(SerializationConfig.Feature.AUTO_DETECT_IS_GETTERS, false);
            mObjectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }
    }

    public final static Parser getInstance() {
        if (Parser.mInstance == null) {
            synchronized (Parser.class) {
                if (Parser.mInstance == null) {
                    Parser.mInstance = new Parser();
                }
            }
        }
        return Parser.mInstance;
    }

    // ///////////////////


    public String serialize(Object object) {
        try {
            return mObjectMapper.writeValueAsString(object);
        } catch (JsonGenerationException e) {
            Log.w(TAG, e);
        } catch (JsonMappingException e) {
            Log.w(TAG, e);
        } catch (IOException e) {
            Log.w(TAG, e);
        }
        return null;
    }

    public  <T> T deserialize(Class<T> classResult, String content) {
        if (content != null) {
            try {
                return mObjectMapper.readValue(content, classResult);
            } catch (JsonParseException e) {
                Log.w(TAG, e);
            } catch (JsonMappingException e) {
                Log.w(TAG, e);
            } catch (IOException e) {
                Log.w(TAG, e);
            }
        }
        return null;
    }

}
